﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.ServiceModel;
using System.Xml.Serialization;
using System.Net.Http;

namespace Site3AI.Controllers
{
    
    public class WeiXinSvcController : ApiController
    {

        const string WEIXINTOKEN="site3aitokenforweixin";
        Models.SiteDbEntities _db = null;
        Models.SiteDbEntities DB
        {
            get {
                return _db ?? (_db = new Models.SiteDbEntities());
            } 
        }

        /// <summary>
        /// 开发者提交信息后，微信服务器将发送GET请求到填写的URL上，GET请求携带四个参数：
        ///参数	描述
        ///signature	 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        ///timestamp	 时间戳
        ///nonce	 随机数
        ///echostr	 随机字符串
        ///开发者通过检验signature对请求进行校验（下面有校验方式）。
        ///若确认此次GET请求来自微信服务器，请原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败。

        ///加密/校验流程如下：
        ///1. 将token、timestamp、nonce三个参数进行字典序排序
        ///2. 将三个参数字符串拼接成一个字符串进行sha1加密
        ///3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        /// </summary>
        /// <returns>echostr</returns>
        public string Get(string signature, string timestamp, string nonce, string echostr)
        {
            return (  signature + timestamp + nonce + echostr);

            string[] ks = new[] { WEIXINTOKEN, timestamp, nonce };
            DB.WeiXinEchoLogs.Add(new Models.WeiXinEchoLog() { 
                Id=Guid.NewGuid(),
                Timemark=DateTime.Now, 
                Signature=signature,
                Timestamp=timestamp,
                Nonce=nonce,
                Echostr=echostr
            });
            DB.SaveChanges();
            Array.Sort<string>(ks);
            var sig = string.Empty;
            var errorstr = "signature not match";
            using (var sha1 = System.Security.Cryptography.SHA1.Create())
            {
                var s = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(string.Join("", ks)));
                sig = BitConverter.ToString(s).Replace("-", "");
            }
            return ((sig.Equals(signature, StringComparison.CurrentCultureIgnoreCase)) ? echostr : errorstr);
        }

        public string Post([FromBody] string rawmsg)
        {
            DB.WeiXinRawMessages.Add(new Site3AI.Models.WeiXinRawMessage() { Id = Guid.NewGuid(), Timemark = DateTime.Now, RawMsg = rawmsg });
            DB.SaveChanges();

            System.Xml.Linq.XElement xe = System.Xml.Linq.XElement.Parse(rawmsg);

            var replayto = xe.Element("FromUserName").Value;
            var replayfrom = xe.Element("ToUserName").Value;
            var replaymsgtype = "text";
            var replaytime = DateTime.Now.ToString("yyyyMMddHHmmss");
            var replaycontent = "问答和菜单正在调试，暂时不提供功能，正式完成后会及时告知大家。谢谢支持！\r\n";
            var msgtype = xe.Element("MsgType").Value;

            var rs = @"<xml>
<ToUserName><![CDATA[{0}]]></ToUserName>
<FromUserName><![CDATA[{1}]]></FromUserName>
<CreateTime>{2}</CreateTime>
<MsgType><![CDATA[{3}]]></MsgType>
<Content><![CDATA[{4}]]></Content>
</xml>";

            var rsnews = @"<xml>
<ToUserName><![CDATA[{0}]]></ToUserName>
<FromUserName><![CDATA[{1}]]></FromUserName>
<CreateTime>{2}</CreateTime>
<MsgType><![CDATA[{3}]]></MsgType>
<ArticleCount>1</ArticleCount>
<Articles>
<item>
<Title><![CDATA[{4}]]></Title> 
<Description><![CDATA[{5}]]></Description>
<PicUrl><![CDATA[{6}]]></PicUrl>
<Url><![CDATA[{7}]]></Url>
</item>
</Articles>
</xml> ";

            if (msgtype == "event" && xe.Element("Event").Value == "CLICK")
            {
                replaycontent += "CLICKED:" + xe.Element("EventKey").Value;
            }
            else if (msgtype == "text")
            {
                replaycontent += "INPUT:" + xe.Element("Content").Value;
            }

            //return Content(string.Format(rs,replayto,replayfrom,replaytime,replaymsgtype,replaycontent));
            return (string.Format(rsnews, replayto, replayfrom, replaytime, "news", replaycontent,
                "点击这里访问主站", "http://sky3ab.com/Content/SliderImgs/logon04.png", "http://www.3ab.com.cn?wxuid=" + replayto
                ));

        }        
    }
}
